/**
 * Created by coder on 2017/12/25.
 */
import React,{Component} from 'react'
import PropTypes from 'prop-types'
import {View,Text,Dimensions,StyleSheet,TouchableWithoutFeedback,Alert} from 'react-native'
import {keyboardW5,keyboardW4,gridMarginLeft} from './common/CommonSize'
import KeyboardNumButton from './KeyboardNumButton'
import KeyboardWordButton from './KeyboardWordButton'
import {connect} from 'react-redux'
import {ACTION_KEYBOARD_FILTER,ACTION_UPDATE_CUR_CELL,ACTION_KEYBOARD_SHOW,ACTION_UPDATE_CELLS,ACTION_SET_CUR_CELL,ACTION_KEYBOARD_SETTING,ACTION_UPDATE_ERROR_MAP,ACTION_FINISH_CUR_LEVEL} from './store/action'
import { NavigationActions ,StackRouter} from 'react-navigation'
import {indexOfClass} from './common/data'
import updateErrorMap from './common/updateErrorMap'
import {store} from './store'
import {addMemory,undoAction,redoAction} from './common/memoryAction'


class Keyboard extends Component{
	constructor(props){
		super(props);

		this.state = {
			filter:false,
			enableUndo:false,
			enableRedo:false,
		};
	}

	isFinish = () => {
		const {cells,errorMap} = store.getState();
		for(let i=0;i<81;i++){
			const cell = cells[i];
			if(cell.isMark || cell.data === 0)
				return false;
		}

		for(let i=0;i<81;i++){
			const cell = errorMap[i];
			if(cell)
				return false;
		}

		return true;
	};

	doFinishAction = () => {
		const {navigation,totalLevel} = this.props;
		const {classIndex,level} = navigation.state.params;

		this.props.finishCurLevel(classIndex,level);

		const {routes} = this.props.nav;
		let newRoutes = routes.slice();
		newRoutes.pop();
		newRoutes.push({routeName:'Main',params:{classIndex,level:level+1}});

		const resetAction = NavigationActions.reset({
			index: newRoutes.length-1,
			actions: newRoutes
		});

		if(level + 1 < totalLevel){
			Alert.alert('完成','恭喜你，成功完成了本关！',
				[
					{text:"回到上一页", onPress:() => {
						navigation.goBack();
					}},
					{text:"下一关", onPress:() => {
						navigation.dispatch(resetAction);
					}},
				],
				{ cancelable: false }
			);
		} else {
			Alert.alert('完成','恭喜你，已经成功完成了所有关卡！',
				[
					{text:"回到上一页", onPress:() => {
						navigation.goBack();
					}},
				],
				{ cancelable: false }
			);
		}
	};


	buttonPress = (name) => {
		const {curCell,mark} = this.props;

		if(typeof name === 'number'){
			if(mark){
				//做标记
				let newArr = curCell.numMark.slice();
				newArr[name-1] = !newArr[name-1];
				this.props.updateCurCell(name,mark,newArr);

				/*if(curCell.data > 0){
					let newCell = Object.assign({},curCell,{data:0});
					this.props.updateCells(newCell,true);
					//this.updateErrorMap(newCell);
					this.props.setErrorMap(newCell);
				}*/

			} else {
				let newCell = Object.assign({},curCell,{data:name,isMark:false,numMark:[false,false,false,false,false,false,false,false,false]});
				this.props.setCurCell(newCell);
				this.props.updateCells(newCell,true);

				this.props.showKeyboard(false);
				this.props.setErrorMap(newCell);
				this.props.addMemory();

				if(this.isFinish()){
					this.doFinishAction();
				}

			}
		} else if(name === '?'){
			this.props.pressFilter();
		} else if(name === 'mark'){
			this.props.setKeyboard({mark:!mark});
		} else if(name === 'clear'){
			this.props.updateCurCell(name,mark,[]);
			if(curCell.data > 0){
				let newCell = Object.assign({},curCell,{data:0});
				this.props.updateCells(newCell,true);
				//this.updateErrorMap(newCell);
				this.props.setErrorMap(newCell);
			}
		} else if(name === 'undo'){
			this.props.undoAction();
		} else if(name === 'redo'){
			this.props.redoAction();
		}
	};

	render(){
		const {numEnable,curCell,style,filter,mark,undo,redo} = this.props;
		const {enableUndo,enableRedo} = this.state;
		const {numMark} = curCell;

		return (
			<View style={[style,styles.mainView]}>
				<View style={styles.rowButton}>
					{
						[1,2,3,4,5].map((item,index) => {
							return (
								<KeyboardNumButton
									key={index}
									buttonPress={this.buttonPress}
									value={item}
									numEnable={filter ? numEnable[index] : true}
								  numMark={numMark[index]}
								/>
							)
						})
					}
				</View>
				<View style={styles.rowButton}>
					{
						[6,7,8,9].map((item,index) => {
							return (
								<KeyboardNumButton
									key={index}
									buttonPress={this.buttonPress}
									value={item}
									numEnable={filter ? numEnable[index+5] : true}
									numMark={numMark[index+5]}
								/>
							)
						})
					}

					<KeyboardWordButton
						buttonPress={this.buttonPress}
					  value=""
					  name="?"
					  iconName="podcast"
					  width={keyboardW5}
					  enable={true}
					  hot={filter}
					/>
				</View>

				<View style={styles.rowButton}>
					<KeyboardWordButton
						buttonPress={this.buttonPress}
						value="撤销"
						name="undo"
						iconName="undo"
						width={keyboardW4}
						enable={undo.length > 0}
					  hot={false}
					/>

					<KeyboardWordButton
						buttonPress={this.buttonPress}
						value="恢复"
						name="redo"
						iconName="repeat"
						width={keyboardW4}
						enable={redo.length > 0}
					  hot={false}
					/>

					<KeyboardWordButton
						buttonPress={this.buttonPress}
						value="清除"
						name="clear"
						iconName="trash-o"
						width={keyboardW4}
						enable={true}
					  hot={false}
					/>

					<KeyboardWordButton
						buttonPress={this.buttonPress}
						value="标记"
						name="mark"
						iconName="bookmark-o"
						width={keyboardW4}
						enable={true}
					  hot={mark}
					/>
				</View>
			</View>
		);
	}
}

Keyboard.propTypes = {

};

const styles = StyleSheet.create({
	mainView:{
		marginLeft:gridMarginLeft,
		marginRight:gridMarginLeft,
	},
	rowButton:{
		flexDirection:'row',
	},
});

const mapStateToProps = (state,ownProps) => {
	const {classIndex,level} = ownProps.navigation.state.params;
	const className = indexOfClass[classIndex];

	return {
		filter:state.keyboard.filter,
		numEnable:state.keyboard.numEnable,
		mark:state.keyboard.mark,
		curCell:state.curCell,
		cells:state.cells,
		errorMap:state.errorMap,
		nav:state.nav,
		totalLevel:state.level[className].totalLevel,
		undo:state.memory.undo,
		redo:state.memory.redo,
	}
};

const mapDispatchToProps = {
	pressFilter:() => {
		return {
			type:ACTION_KEYBOARD_FILTER,
		};
	},
	updateCurCell:(value,isMark,numMark) => {
		return {
			type:ACTION_UPDATE_CUR_CELL,
			payload:{
				value,isMark,numMark
			}
		};
	},
	setCurCell:(cell) => {
		return {
			type:ACTION_SET_CUR_CELL,
			payload:{
				cell
			}
		}
	},
	showKeyboard:(show)=>{
		return {
			type:ACTION_KEYBOARD_SHOW,
			payload:{
				show
			}
		};
	},
	updateCells:(cell,needRecreate) => {
		return {
			type:ACTION_UPDATE_CELLS,
			payload:{
				x:cell.x,
				y:cell.y,
				cell,
				needRecreate,
			}
		};
	},
	setKeyboard:(setting) => {
		return {
			type:ACTION_KEYBOARD_SETTING,
			payload:setting,
		};
	},
	setErrorMap:(newCell) => {
		return updateErrorMap(newCell);
	},
	finishCurLevel:(classIndex,level) => {
		return {
			type:ACTION_FINISH_CUR_LEVEL,
			payload:{
				classIndex,
				level
			}
		}
	},
	addMemory:addMemory,
	undoAction:undoAction,
	redoAction:redoAction,

};

export default connect(mapStateToProps,mapDispatchToProps)(Keyboard);